package com.example.my.android;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private Button okButton;
    private EditText usernameEdit;
    private EditText passwordEdit;
    private CheckBox rememberCheck;
    private CheckBox autoLoginCheck;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        usernameEdit = findViewById(R.id.username_edit);
        passwordEdit = findViewById(R.id.password_edit);
        rememberCheck = findViewById(R.id.remember_check);
        autoLoginCheck = findViewById(R.id.auto_check);

        okButton = findViewById(R.id.ok_button);//R文件，Resource，资源
        okButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = usernameEdit.getText().toString();
                String password = passwordEdit.getText().toString();
                if("abc".equals(username) && "123".equals(password)){
                    System.out.println("允许进入");

                    //TODO：如果选中了记住用户名复选框的话，就将用户名和密码保存在首选项文件中
                    SharedPreferences preferences = getSharedPreferences("auto.pref", MODE_PRIVATE);
                    SharedPreferences.Editor editor = preferences.edit();
                    editor.putString("username", username);
                    editor.putString("password", password);
                    editor.putBoolean("remember", rememberCheck.isChecked());
                    editor.putBoolean("auto", autoLoginCheck.isChecked());
                    editor.commit();

                    Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
                    startActivity(intent);

                    finish();
                }else{
                    Toast.makeText(getApplicationContext(),
                            "用户名或密码错误，请重新输入。",
                            Toast.LENGTH_LONG).show();
                }
            }
        });

        //TODO:加载首选项中的参数
        SharedPreferences preferences = getSharedPreferences("auto.pref", MODE_PRIVATE);
        String username = preferences.getString("username", "");
        String password = preferences.getString("password", "");
        boolean remember = preferences.getBoolean("remember", false);
        boolean autoLoin = preferences.getBoolean("auto", false);

        if(remember==true) {
            usernameEdit.setText(username);
            passwordEdit.setText(password);
        }
        rememberCheck.setChecked(remember);
        autoLoginCheck.setChecked(autoLoin);
    }
}